/**
 * 科室选择框
 *
 * @author banglong
 * @date 2016/8/19.
 */
define(['Layer', 'text!../html/components/common/depSelectTemp.html!strip', 'layPage', 'rootPath', 'avalon', 'tools'],
  function (layer, htmlTemp, laypage, rootPath, avalon, tools) {

    laypage.dir = rootPath.getRootPath() + 'js/common/laypage/skin/laypage.css'; // 设定路径

    var chooseDespFunc; // 定义选择科室的事件
    var layeroObj; // 显示框隐藏 不销毁
    var $page; // page对象
    var depsCopy; // 科室集合的复制
    var $searchInput;

    var layeroObjHide = function () {
      layer.close(layeroObj);
    };
    var depSelect; // 定义 科室选择框的 vm对象
    var getVmOption = function () {
      return {
        $id: 'dpeSelect',
        deps: [],
        size: 10, // 大小
        pages: 0, // 页数
        count: 0, // 总数
        active: 'active', // 单击效果
        chooseIndex: 0, // 单击选择的index
        searchInput: '', //选择输入框 （拼音码或名称）

        hideDialog: function () { // 隐藏选择框
          layeroObjHide();
        },

        handleClick: function (index) { // 单击事件
          depSelect.chooseIndex = index;
        },

        handleDBClick: function (index) { //双击事件
          if (typeof chooseDespFunc === 'function') {
            chooseDespFunc(depSelect.deps[index]);
          }
          layeroObjHide();
        },

        sureDesp: function () { // 确定事件
          if (typeof chooseDespFunc === 'function' && depSelect.deps.length !== 0) {
            chooseDespFunc(depSelect.deps[depSelect.chooseIndex]);
            layeroObjHide();
          }
        },

        handleSubmit: function (e) {
          e.preventDefault();
          if (typeof chooseDespFunc === 'function' && depSelect.deps.length !== 0) {
            chooseDespFunc(depSelect.deps[depSelect.chooseIndex]);
            layeroObjHide();
          }
        },

        handleSearch: function () { // 搜索
          reInitDespTable(depSelect.searchInput);
        },

        handleKeydown: function (e) {
          var theEvent = e || window.event;
          var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
          switch (code) {
            case 13:
              return;
              break;
            case 27:
              e.preventDefault();
              layeroObjHide();
              break;
            case 38:
              e.preventDefault();
              if (depSelect.chooseIndex !== 0) {
                depSelect.chooseIndex--;
              }
              break;
            case 40:
              e.preventDefault();
              if (depSelect.chooseIndex < (depSelect.deps.length - 1)) {
                depSelect.chooseIndex++;
              }
              break;
          }
        }
      };
    };

    /**
     * 由新的数组来重新构建 pages
     */
    function reInitDespTable(searchValue) {
      depSelect.chooseIndex = 0;
      var newDeps;
      if (searchValue) {
        var substrRegex = new RegExp(searchValue, 'i');
        newDeps = depsCopy.filter(function (data) {
          if (substrRegex.test(data['Pysx'])) {
            return true;
          }
          if (substrRegex.test(data['Ksdm'])) {
            return true;
          }
          return !!substrRegex.test(data['Ksmc']);
        });
      } else {
        newDeps = depsCopy.concat();
      }
      initPage($page, newDeps); //再次初始化分页信息
    }

    /**
     * 构建分页信息
     *
     * @param deps
     */
    function buildPageInfo(deps) {
      depSelect.pages = deps.length === 0 ? 0 : Math.ceil(deps.length / 10);
      depSelect.count = deps.length;
    }

    /**
     * 构建分页组件
     *
     * @param page page id
     * @param desps 科室数组
     */
    function initPage(page, desps) {
      $page.html('');
      buildPageInfo(desps); // 首先构建分页信息
      laypage({
        cont: page,
        pages: depSelect.pages,
        jump: function (obj, first) {
          //得到了当前页，用于向服务端请求对应数据
          var curr = obj.curr;
          var truePages = curr - 1;
          depSelect.deps.splice(0, 10);
          depSelect.deps.pushArray(desps.slice(truePages * 10, truePages * 10 + 10));
        }
      });
      $('.layui-layer-content').css('overflow', 'hidden');
    }


    function focusOnSearchInput() {
      setTimeout(function () {
        $searchInput.focus();
      }, 200);
    }

    function handleSearchValue(searchValue) {
      if (searchValue) { //有初始的查询条件
        reInitDespTable(searchValue);
      } else {
        reInitDespTable('');
      }
      depSelect.searchInput = searchValue || '';
    }

    /**
     * deps 所有的科室
     */
    var init = function (deps, chooseDesp, searchValue) {
      chooseDespFunc = chooseDesp;
      layeroObj = tools.createNewOpenWindow(['800px', '560px'], '科室选择', htmlTemp);
      depSelect = tools.initAvalonVm(avalon, getVmOption(), '.depSelectDialogContent');

      $searchInput = document.querySelector('#searchInputForDep'); // 设置焦点
      focusOnSearchInput();

      $page = $('#page');
      depsCopy = deps.slice(0, deps.length); // 复制科室数组 留着检测
      handleSearchValue(searchValue);
    };

    return {
      init: init
    }
  });